package com.weayer.service.Impl;

import com.weayer.constant.CommonStatusEnum;
import com.weayer.dto.ResponseResult;
import com.weayer.request.DriverGrabRequest;
import com.weayer.service.GrabService;
import com.weayer.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @description: 自定义 Redis
 * @author: Weayer
 **/
@Service("diyRedisGrabService")
public class DiyRedisGrabServiceImpl implements GrabService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    RenewRedisLock renewRedisLock;

    @Override
    public ResponseResult grab(DriverGrabRequest driverGrabRequest) {
        String key = driverGrabRequest.getOrderId() + "";
        String value = driverGrabRequest.getDriverId() + "-" + UUID.randomUUID();
        // 当不存在key时，加锁并设置过期时间
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, value, 30, TimeUnit.SECONDS);
        // 锁续期，对于30s过期时间，每经过10s后续期一次（解决程序还在执行，锁过期的问题）
        renewRedisLock.renewRedisLock(key, value, 30);
        ResponseResult result = null;
        if(flag){
            System.out.println("异步执行：抢单");
            // 模拟程序执行时间
            try {
                TimeUnit.SECONDS.sleep(40);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 抢单
            result = orderInfoService.grab(driverGrabRequest);
            // 删除锁（仅删除当前请求的锁）
            if(stringRedisTemplate.opsForValue().get(key).equals(value)){
                stringRedisTemplate.delete(key);
            }
        }else{
            result = ResponseResult.fail(CommonStatusEnum.ORDER_GRABBING.getCode(), CommonStatusEnum.ORDER_GRABBING.getValue());
        }
        return result;
    }

}
